<template>
  <Card :bordered="false" dis-hover bordered>
    <Layout>
      <Header class="header-grids space-left-small">
        <Row>
          <Button size="default" type="primary" @click="addChildNode">添加子部门</Button>
          <Button size="default" class="space-left" @click="addTopNode">添加顶级部门</Button>
          <Button size="default" type="error" class="space-left" @click="openDeleteModal">批量删除</Button>
          <Button size="default" type="default" class="space-left" @click="refreshNodes">刷新</Button>
          <Switch size="large" class="space-left" v-model="isCascade">
            <span slot="open">级联</span>
            <span slot="close">单选</span>
          </Switch>
        </Row>
      </Header>
    </Layout>
    <Layout>
      <Sider class="side-node space-left">
        <Row>
          <Alert style="height:40px" show-icon>当前选择编辑：
            <Button class="select-title text-btn" style="padding: 0 15px 0" size="large" v-text="checkedNode.name"
                    type="text">
            </Button>
          </Alert>
        </Row>
        <Row>
          <Input suffix="ios-search" placeholder="输入部门名称搜索" width="100%" v-model="searchWord" @input="searchTree"/>
        </Row>
        <Row style="max-height: 648px;overflow-x:hidden; overflow-y:auto;">
          <Tree :data="depttree" ref="tree" show-checkbox :check-strictly="!isCascade"
                @on-select-change="selectTreeDept"
                :render="renderContent"></Tree>
          <Spin size="large" fix v-if="spinShow"></Spin>
        </Row>
      </Sider>
      <Content class="space-left">
        <Row>
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
            <FormItem label="部门简称" prop="name">
              <Input v-model="formValidate.name" class="form-input-length" placeholder="输入部门简称"/>
            </FormItem>
            <FormItem label="部门全称" prop="title">
              <Input v-model="formValidate.title" class="form-input-length" placeholder="输入部门全称"/>
            </FormItem>
            <FormItem label="排序值" prop="sort">
              <InputNumber :max="10" :min="1" v-model="formValidate.sort"></InputNumber>
            </FormItem>
            <FormItem label="部门类型" prop="grouptype">
              <Select v-model="formValidate.grouptype" :value="formValidate.grouptype" class="form-input-length">
                <Option v-for="group in groupList" :value="group.value" :key="group.value">
                  <i :class="group.icon"></i>
                  {{ group.label }}
                </Option>
              </Select>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="handleSubmit('formValidate')">修改并保存</Button>
              <Button @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
            </FormItem>
          </Form>
        </Row>
      </Content>
    </Layout>


    <!--子节点模态框-->
    <Modal loading closable v-model="childNodeModel" ref="childNodeModel" draggable scrollable title="添加子部门(可拖动)">
      <Form ref="childForm" :model="childForm" :rules="ruleValidate" :label-width="100">
        <FormItem label="上级部门名称">
          <Tag type="dot" color="primary">{{checkedNode.name}}</Tag>
        </FormItem>
        <FormItem label="部门简称" prop="name">
          <Input v-model="childForm.name" class="form-input-length" placeholder="输入部门简称"/>
        </FormItem>
        <FormItem label="部门全称" prop="title">
          <Input v-model="childForm.title" class="form-input-length" placeholder="输入部门全称"/>
        </FormItem>
        <FormItem label="排序值" prop="sort">
          <InputNumber :max="10" :min="1" v-model="childForm.sort"></InputNumber>
        </FormItem>
        <FormItem label="部门类型" clearable prop="grouptype">
          <Select v-model="childForm.grouptype" class="form-input-length">
            <Option v-for="group in groupList" :value="group.value" :key="group.value">
              <i :class="group.icon"></i>
              {{ group.label }}
            </Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer" style="margin-left: 340px;">
        <Button type="default" size="large" @click="childNodeCancel('childForm')">取消</Button>
        <Button type="primary" size="large" @click="childNodeOk('childForm')">提交</Button>
      </div>
    </Modal>

    <!--顶级节点模态框-->
    <Modal loading closable v-model="topNodeModel" ref="topNodeModel" draggable scrollable title="添加顶级节点(可拖动)">
      <Form ref="topForm" :model="topForm" :rules="ruleValidate" :label-width="100">
        <FormItem label="部门简称" prop="name">
          <Input v-model="topForm.name" class="form-input-length" placeholder="输入部门简称"/>
        </FormItem>
        <FormItem label="部门全称" prop="title">
          <Input v-model="topForm.title" class="form-input-length" placeholder="输入部门全称"/>
        </FormItem>
        <FormItem label="排序值" prop="sort">
          <InputNumber :max="10" :min="1" v-model="topForm.sort"></InputNumber>
        </FormItem>
        <FormItem label="部门类型" prop="grouptype">
          <Select v-model="topForm.grouptype" class="form-input-length">
            <Option v-for="group in groupList" :value="group.value" :key="group.value">
              <i :class="group.icon"></i>
              {{ group.label }}
            </Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer" style="margin-left: 340px;">
        <Button type="default" size="large" @click="topNodeCancel('topForm')">取消</Button>
        <Button type="primary" size="large" @click="topNodeOk('topForm')">提交</Button>
      </div>
    </Modal>
    <!--批量删除时的弹窗提示-->
    <Modal
      title="提示"
      v-model="deleteModal"
      class-name="vertical-center-modal">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>删除提示</span>
      </p>
      <div style="text-align:center">
        <p>确定要删除选中的部门节点及其下面的所有子节点？
        </p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long @click="deleteNodes">确定</Button>
      </div>
    </Modal>
  </Card>
</template>

<script>
  import {addDeptNode, batchDeleteNodes, getDeptList, updateDeptNode} from '@/api/dept'


  export default {
    name: 'rolemgt',
    data() {
      return {
        spinShow: false,//Spin loading样式
        checkedNode: '',
        childNodeModel: false,
        topNodeModel: false,
        isCascade: true,//默认是级联  false 则代表单选
        //右侧表单
        formValidate: {
          name: '',
          sort: 0,
          title: "",
          grouptype: '',
        },
        //添加子节点 model
        childForm: {
          name: '',
          sort: 0,
          title: "",
          grouptype: '',
        },
        //添加顶级节点 model
        topForm: {
          name: '',
          sort: 0,
          title: "",
          grouptype: '',
        },
        ruleValidate: {
          name: [
            {required: true, message: '名称不能为空', trigger: 'blur'}
          ],
          title: [
            {required: true, message: '部门全称不能为空', trigger: 'blur'}
          ],
          grouptype: [
            {required: true, message: '部门类型不能为空', trigger: 'blur'}
          ],
        },
        depttree: [],
        groupList: [
          {
            label: "系统",
            value: "1",
            icon: "ivu-icon ivu-icon-md-desktop space-little",
          },
          {
            label: "公司",
            value: "2",
            icon: "ivu-icon ivu-icon-ios-contacts space-little",
          },
          {
            label: "子公司",
            value: "3",
            icon: "ivu-icon ivu-icon-ios-contact space-little",
          },
          {
            label: "部门",
            value: "4",
            icon: "ivu-icon ivu-icon-md-podium space-little",
          },
        ],
        deleteModal: false,
        checkedIds: [],
        searchWord: "",//部门名称
        efficientSearchData: [],//提供深度搜索的数据
      }
    },
    methods: {
      initDeptNodes(name) {
        this.spinShow = true;
        getDeptList({name}).then(res => {
          this.spinShow = false;
          const data = res.data;
          //重置选中值
          this.resetForm();
          this.depttree = [];
          this.depttree.push(...data);
          this.efficientSearchData = this.depttree;
        }).catch(err => {
          this.spinShow = false;
          console.error("获取部门列表信息出错! " + err)
        })
      },
      refreshNodes() {
        this.initDeptNodes(this.searchWord);
      },
      addChildNode() {
        //校验1： 不存在已选中的节点,提示
        if (!this.checkedNode) {
          this.$Message["warning"]({background: true, content: '请点击选择要修改的部门节点'});
          return false;
        }
        //校验2： 只允许添加到 level小于5的按钮权限层级
        if (this.checkedNode.level === 5) {
          this.$Modal.warning({
            title: "提示",
            content: '不能添加啦，当前部门深度仅允许扩展至第六级'
          });
          return false;
        }
        //重置
        this.resetChildForm('childForm');
        this.$refs.childForm.resetFields();
        this.childNodeModel = true;
      },
      addTopNode() {
        this.resetTopForm('topForm');
        this.$refs.topForm.resetFields();
        //打开模态框
        this.topNodeModel = true;
      },
      openDeleteModal() {
        this.checkedIds = [];
        let checkedNodes = this.$refs.tree.getCheckedNodes();
        if (checkedNodes !== undefined && checkedNodes.length > 0) {
          checkedNodes.forEach((item, index) => {
            this.checkedIds.push(item.id);
          });
          this.deleteModal = true;
        } else {
          this.$Message["warning"]({background: true, content: "请先选择需要删除的部门节点"});
        }
      },
      selectTreeDept(arr, data) {
        //变更提示信息中的数据
        this.$refs.formValidate.resetFields();
        this.renderForm(data);
      },
      renderForm(data) {
        this.checkedNode = data;
        this.formValidate.title = data.title;
        this.formValidate.name = data.name;
        this.formValidate.sort = data.sort;
        this.formValidate.grouptype = data.grouptype;
      },

      resetForm() {
        this.checkedNode = "";
        this.formValidate.title = "";
        this.formValidate.name = "";
        this.formValidate.grouptype = "";
        this.formValidate.sort = 0;
      },
      resetChildForm() {
        this.childForm.title = "";
        this.childForm.name = "";
        this.childForm.grouptype = "";
        this.childForm.sort = 0;
      },
      resetTopForm() {
        this.topForm.title = "";
        this.topForm.name = "";
        this.topForm.grouptype = "";
        this.topForm.sort = 0;
      },
      resetSelectedNode() {
        if (this.checkedNode) {
          this.checkedNode.selected = false;
          this.checkedNode = "";
        }
      },
      childNodeOk(name) {
        let childModal = this.$refs.childNodeModel;
        this.$refs[name].validate((valid) => {
          let menuNode = {
            parentId: this.checkedNode.id,
            title: this.childForm.title,
            name: this.childForm.name,
            level: this.checkedNode.level + 1,
            sort: this.childForm.sort,
            grouptype: this.childForm.grouptype,
          };
          if (valid) {
            addDeptNode(menuNode).then(res => {
              this.handleResult(res);
            }).catch(err => {
              this.spinShow = false;
              console.error("添加子菜单出错! " + err)
            });
            //over
            this.resetChildForm('childForm');
            childModal.close();
          } else {
            return false;
          }
        })

      },
      childNodeCancel(name) {
        this.$refs.childNodeModel.close();
      },
      topNodeOk(name) {
        let _that = this;
        let topModal = this.$refs.topNodeModel;
        this.$refs[name].validate((valid) => {
          let menuNode = {
            parentId: 0,
            name: this.topForm.name,
            title: this.topForm.title,
            level: 0,
            sort: this.topForm.sort,
            grouptype: this.topForm.grouptype,
          };
          if (valid) {
            addDeptNode(menuNode).then(res => {
              this.handleResult(res);
            }).catch(err => {
              this.spinShow = false;
              console.error("添加顶级部门出错! " + err)
            });
            //结束
            this.resetTopForm('topForm');
            topModal.close();
          } else {
            return false;
          }
        })

      },
      topNodeCancel(name) {
        this.$refs.topNodeModel.close();
      },
      searchTree() {
        this.initDeptNodes(this.searchWord);
      },
      handleReset(name) {
        if (this.$refs[name] !== undefined) {
          this.$refs[name].resetFields();
          this.resetSelectedNode();
        }
      },
      handleSubmit(name) {
        let _that = this;
        if (!_that.checkedNode) {
          this.$Message["warning"]({background: true, content: '请点击选择要修改的部门节点'});
          return false;
        }
        this.$refs[name].validate((valid) => {
          if (valid) {
            let deptNode = {
              id: _that.checkedNode.id,
              parentId: _that.checkedNode.parentId,
              grouptype: _that.checkedNode.grouptype,
              name: this.formValidate.name,
              title: this.formValidate.title,
              sort: this.formValidate.sort,
            };
            updateDeptNode(deptNode).then(res => {
              let data = res.data;
              let message = data.message;
              let code = data.code;
              if (code === 200) {
                this.$Message.success(message);
                this.initDeptNodes(this.searchWord);
              }
              if (code === 500) {
                this.$Message["warning"]({background: true, content: message});
              }
            }).catch(err => {
              console.error("更新部门节点时出错!" + err)
            });
          }
        })
      },
      handleResult(res) {
        let data = res.data;
        let message = data.message;
        let code = data.code;
        if (code === 200) {
          this.$Message.success(message);
          this.initDeptNodes(this.searchWord);
        }
        if (code === 500) {
          this.$Message["warning"]({background: true, content: message});
        }
      },
      deleteNodes() {
        //有节点选中
        if (this.checkedIds && this.checkedIds.length > 0) {
          batchDeleteNodes(this.checkedIds.join(",")).then(res => {
            this.handleResult(res);
          }).catch(err => {
            console.error("批量删除时出现异常:" + err)
          });
          this.deleteModal = false;
        }
      },
      renderContent(h, {root, node, data}) {
        let level = node.node.level;
        return h('span', {
          style: {
            display: 'inline-block',
            width: '100%'
          }
        }, [
          h('span', [
            h('Icon', {
              props: {
                type: level === 1 ? 'ios-eye' : level === 2 ? 'ios-cafe' : level === 3 ? 'ios-build' : level === 4 ? 'ios-brush' : level === 5 ? 'ios-bulb' : 'ios-cloud'
              },
              style: {
                marginRight: '8px'
              }
            }),
            h('span',
              {
                style: {
                  display: "inline-block",
                  cursor: "pointer",
                  background: node.node.selected ? "#d5e8fc" : "#fff", //根据选中状态设置样式
                  color: node.node.selected ? "#515a6e" : "#515a6e",
                  borderRadius: "3px",
                  padding: "3px"
                },
                on: {
                  click: () => {
                    if (!node.node.selected)
                      this.$refs.tree.handleSelect(node.nodeKey); //手动选择树节点
                  }
                }
              }, data.title)
          ])

        ]);
      },
    },
    mounted() {
      this.initDeptNodes(this.searchWord);
    }

  }
</script>

<style lang="less">
  @import 'index.less';
</style>
